<!--
 * @FilePath: account.vue
 * @@author: wjj
 * @Date: 2025-08-06 10:01:15
 * @@Description: new js file
-->
<template>
  <el-card style="height: 80px; border-radius: 50px">
    <el-form :inline="true" class="form">
      <el-form-item>
        <el-input
          placeholder="请你输入搜索用户账号"
          v-model="keyword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="default"
          :disabled="keyword ? false : true"
          @click="search"
          v-has="`btn.Account.Token`"
        >
          搜索
        </el-button>
        <el-button
          type="primary"
          size="default"
          @click="reset"
          v-has="`btn.Account.Token`"
        >
          重置
        </el-button>
      </el-form-item>
      <el-form-item label="" v-if="getType()">
        <span style="color: red; font-size: 30px; font-weight: bold">
          目前仅支持NIMI侧,相关功能已经隐藏.
        </span>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px; border-radius: 50px">
    <el-button
      type="primary"
      size="default"
      @click="addUser"
      v-has="`btn.Account.Token`"
    >
      创建账号
    </el-button>
    <el-button
      type="primary"
      size="default"
      :disabled="selectIdArr.length ? false : true"
      @click="updateSelectUser"
      v-has="`btn.Account.Token`"
    >
      批量更新
    </el-button>
    <el-button
      type="primary"
      size="default"
      @click="allUpdater"
      v-has="`btn.Account.Token`"
    >
      全量更新
    </el-button>
    <el-button
      type="primary"
      size="default"
      @click="downloadCsv"
      v-has="`btn.Account.Token`"
    >
      下载
    </el-button>
    <!-- table展示用户信息 -->
    <el-table
      @selection-change="selectChange"
      style="margin: 10px 0px"
      border
      :data="userArr"
      @sort-change="handleSortChange"
      :row-class-name="tableRowClassName"
      height="600"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column
        label="账号"
        align="center"
        prop="account"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="昵称"
        align="center"
        prop="nickname"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="UID"
        align="center"
        prop="uid"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="设备" align="center" show-overflow-tooltip>
        <template #default="scope">
          <div v-if="scope.row.editMode">
            <el-input
              v-model="scope.row.device_id"
              ref="inputRef"
              @blur="confirmEdit(scope.row)"
              @keyup.enter="confirmEdit(scope.row)"
            />
          </div>
          <span
            v-else
            @click="startEdit(scope.row, scope.$index)"
            style="min-height: 3px; min-width: 3px"
          >
            {{ scope.row.device_id }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="token"
        align="center"
        prop="token"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="update_time"
        show-overflow-tooltip
        sortable
        :sort-orders="['ascending', 'descending']"
      ></el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <!-- eslint-disable -->
        <template #="{ row, $index }">
          <el-button
            type="primary"
            :icon="CopyDocument"
            size="small"
            @click="fallbackCopy(row.token)"
          />
          <!-- <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateToken(row)"
            v-has="`btn.User.update`"
          >
            编辑
          </el-button> -->
          <el-button
            type="primary"
            size="small"
            @click="updateToken(row)"
            v-has="`btn.Account.Token`"
          >
            更新
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 50, 100, 200, 500]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHasUser"
      @size-change="handler"
    />
  </el-card>
  <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
  <el-drawer v-model="drawer">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>添加账号</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="账号" prop="account">
          <el-input
            placeholder="请您输入手机号"
            v-model="userParams.account"
          ></el-input>
        </el-form-item>
        <el-form-item label="设备ID" prop="device_id">
          <el-input
            placeholder="请您输入用户昵称"
            v-model="userParams.device_id"
          ></el-input>
        </el-form-item>
        <el-form-item label="递增创建账号个数">
          <el-tooltip class="box-item" effect="dark" placement="top-start">
            <template #content>
              填0就是创建当前账号【18818880000】,
              <br />
              填1就是创建【18818880000,18818880001】,
              <br />
              依次类推
            </template>
            <el-input-number
              v-model="addMore"
              :min="0"
              :max="10000"
            ></el-input-number>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="头像ID">
          <el-input
            placeholder="请您输入头像ID"
            v-model="fid"
            disabled
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 抽屉结构:用户某一个已有的账号进行职位分配 -->
</template>
 <script setup lang="ts">
import useLayOutSettingStore from '@/store/modules/setting'
import { ref, onMounted, reactive, nextTick, markRaw } from 'vue'
//引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
import useSocketClient from '@/store/socket/socket_client'
import emmit from '@/utils/emitter'
import { useRoute, useRouter } from 'vue-router'
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import {
  updateUserList,
  reqAccountInfo,
  reqAddUser,
  updateUser,
  updateAll,
} from '@/api/nimi/sudu/account'
import type { UserResponseData, User } from '@/api/acl/user/type'
import { Delete, CopyDocument } from '@element-plus/icons-vue'
import { da, el, ro } from 'element-plus/es/locale'
import { fallbackCopy, nimi_login } from '@/utils/common'
defineOptions({
  name: 'NimiAccount',
})
let userStore = useUserStore()
//默认页码
let pageNo = ref<number>(1)
//一页展示几条数据
let pageSize = ref<number>(20)
//用户总个数
let total = ref<number>(0)
//存储全部用户的数组
let userArr = ref<any>([])
//定义响应式数据控制抽屉的显示与隐藏
let drawer = ref<boolean>(false)
let inputRef = ref()
let editIndex = ref<any>(-1)
let type = ref(1)
let fid = ref('179066c16b914843131cf0063ba638a9_1746005082895')
//状态表格
let row_status = ref(false)
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: User
  rowIndex: number
}) => {
  if (rowIndex === 0 && row_status.value) {
    return 'success-row'
  }
  return ''
}
//排序
const handleSortChange = ({ column, prop, order }: any) => {
  console.log(order === 'ascending' ? 'asc' : 'desc')
  getHasUser(pageNo.value, order === 'ascending' ? 'asc' : 'desc')
}
emmit.on('add_account', (data: any) => {
  if (data.code == 200) {
    ElMessage.closeAll()
    ElMessage.success(data.msg)
  } else if (data.code == 201) {
    ElMessage.closeAll()
    ElMessage.success(data.msg)
    getHasUser()
  } else {
    ElMessage.error(data.msg)
  }
})
const getType = () => {
  return userArr.value.length == 0
}
//递增账号数量
let addMore = ref(0)
// let tableData = ref<any[]>([
//   { id: 1, username: '用户1', editMode: false },
//   { id: 2, username: '用户2', editMode: false },
// ])

// //控制分配角色抽屉显示与隐藏
// let drawer1 = ref<boolean>(false)
function startEdit(row: any, index: any) {
  //   if (editIndex.value !== -1) {
  //     // 如果已经有正在编辑的行，先保存
  //     console.log(11111111)
  //     confirmEdit(tableData[editIndex.value])
  //   }
  row.editMode = true
  editIndex.value = index
  nextTick(() => {
    inputRef?.value.focus()
  })
}
function confirmEdit(row: any) {
  console.log(row.device_id)
  if (row.device_id) {
    row.editMode = false
    editIndex.value = -1
  }

  saveData(row)
}
function saveData(row: any) {
  // 调用API保存数据
  console.log('保存数据:', row)
}
//收集用户信息的响应式数据
let userParams = reactive<any>({
  account: '',
  device_id: '',
})
//准备一个数组存储批量更新的用户的ID
let selectIdArr = ref<User[]>([])
//获取form组件实例
let formRef = ref<any>()
//定义响应式数据:收集用户输入进来的关键字
let keyword = ref<string>('')
//获取模板setting仓库
let settingStore = useLayOutSettingStore()
const downloadCsv = () => {
  downloadJSONAsCSV(userArr.value)
}
//下载数据为csv
function downloadJSONAsCSV(jsonData: any[], filename = 'data.csv') {
  // 定义 CSV 头部（列名）
  const headers = ['phone_number', 'user_id', 'token']

  // 处理 JSON 数据为 CSV 行
  const csvRows = []

  // 添加头部行
  // csvRows.push(headers.join(','))
  // 添加 Excel 自动调整列宽的元数据（仅对 Excel 有效）
  // csvRows.push('sep=,') // 指定分隔符
  csvRows.push('\ufeff' + headers.join(',')) // BOM 头确保中文显示正常
  // 添加数据行
  jsonData.forEach((item: { account: any; uid: any; token: any }) => {
    const row = [item.account || '', item.uid || '', item.token || '']

    // 转义包含逗号或引号的值
    const escapedRow = row.map((value) => {
      if (
        typeof value === 'string' &&
        (value.includes(',') || value.includes('"'))
      ) {
        return `"${value.replace(/"/g, '""')}"`
      }
      return value
    })

    csvRows.push(escapedRow.join(','))
  })

  // 创建 CSV 字符串
  const csvString = csvRows.join('\n')

  // 创建 Blob 对象
  const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' })

  // 创建下载链接
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)

  link.setAttribute('href', url)
  link.setAttribute('download', filename)
  link.style.visibility = 'hidden'

  // 触发下载
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
//组件挂载完毕
onMounted(() => {
  getHasUser()
})
//获取全部已有的用户信息
const getHasUser = async (pager = 1, asc = 'desc') => {
  //收集当前页码
  pageNo.value = pager
  let result = await reqAccountInfo(
    pageNo.value,
    pageSize.value,
    keyword.value,
    asc,
  )
  if (result.code == 200) {
    total.value = result.data.total
    userArr.value = result.data.accounts
  }
}
//分页器下拉菜单的自定义事件的回调
const handler = () => {
  getHasUser()
}
//添加用户按钮的回调
const addUser = () => {
  //抽屉显示出来
  drawer.value = true
  //清空数据
  Object.assign(userParams, {
    account: '',
    device_id: '185ae413009a8ac1',
    type: type.value,
  })
  addMore.value = 0
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('account')
  })
}
//更新已有的用户按钮的回调
//row:即为已有用户的账号信息
const updateToken = async (row: any) => {
  if (row.device_id == '') {
    ElMessage.error('设备ID不能为空')
    return
  }
  //保存按钮:添加新的用户|更新已有的用户账号信息
  let result: any = await updateUser(type.value, row.id, row.device_id)

  //添加或者更新成功
  if (result.code == 200) {
    //提示消息
    ElMessage({
      type: 'success',
      message: '更新成功',
    })
  } else {
    //提示消息
    ElMessage({
      type: 'error',
      message: '更新失败',
    })
  }
  getHasUser()
  row_status.value = true
}
//保存按钮的回调
const save = async () => {
  //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
  await formRef.value.validate()

  //保存按钮:添加新的用户|更新已有的用户账号信息
  let result: any = await reqAddUser({
    account: userParams.account,
    device_id: userParams.device_id,
    addMore: addMore.value,
    type: type.value,
    fid: fid.value,
  })

  //添加或者更新成功
  if (result.code == 200) {
    //关闭抽屉
    drawer.value = false
    //提示消息
    ElMessage({
      type: 'success',
      message: result.msg,
    })
    //获取最新的全部账号的信息
    // getHasUser(userParams.id ? pageNo.value : 1)
    //浏览器自动刷新一次,重新获取用户信息（修改自己）
    // window.location.reload()
  } else {
    //关闭抽屉
    drawer.value = false
    //提示消息
    ElMessage({
      type: 'error',
      message: result.msg,
    })
  }
  setTimeout(() => {
    getHasUser()
  }, 50)
  getHasUser()
}
//取消按钮的回调
const cancel = () => {
  //关闭抽屉
  drawer.value = false
}
function isMobilePhone(phone: any) {
  // 中国大陆手机号正则（11位，1开头，第二位3-9）
  const reg = /^1[3-9]\d{9}$/
  return reg.test(phone)
}
//校验用户名字回调函数
const validatorUsername = (rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (!isMobilePhone(value.trim())) {
    callBack(new Error('请填写正确的手机号'))
  } else {
    callBack()
  }
}

//表单校验的规则对象
const rules = {
  //用户账号device_id
  account: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  device_id: [{ required: true, trigger: 'blur' }],
}

//table复选框勾选的时候会触发的事件
const selectChange = (value: any) => {
  selectIdArr.value = value
}
//批量更新按钮的回调
const allUpdater = async () => {
  // TODO ElMessageBox使用
  ElMessageBox.confirm('确定全量更新成员吗?', '全量更新', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    //自定义图标
    icon: markRaw(Delete),
    //设置draggable属性为true来开启拖拽弹窗能力。 设置 overflow为 true 可以让拖拽范围超出可视区。
    draggable: true,
    overflow: true,
  })
    .then(async () => {
      //更新的请求
      let result: any = await updateAll(type.value)
      if (result.code == 200) {
        ElMessage({ type: 'success', message: result.msg })
      } else {
        ElMessage({ type: 'error', message: result.msg })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消全量更新操作',
      })
    })
}
//批量更新按钮的回调
const updateSelectUser = async () => {
  // TODO ElMessageBox使用
  ElMessageBox.confirm('确定批量更新成员吗?', '批量更新', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    //自定义图标
    icon: markRaw(Delete),
    //设置draggable属性为true来开启拖拽弹窗能力。 设置 overflow为 true 可以让拖拽范围超出可视区。
    draggable: true,
    overflow: true,
  })
    .then(async () => {
      //整理批量更新的参数
      let idsList: any = selectIdArr.value.map((item) => {
        return item.id
      })
      //批量更新的请求
      let result: any = await updateUserList(type.value, idsList)
      if (result.code == 200) {
        ElMessage({ type: 'success', message: result.msg })
        // getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
      } else {
        ElMessage({ type: 'error', message: result.msg })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消批量更新操作',
      })
    })
}

//搜索按钮的回调
const search = () => {
  //根据关键字获取相应的用户数据
  getHasUser()
  //清空关键字
  keyword.value = ''
}
//重置按钮
const reset = () => {
  settingStore.refsh = !settingStore.refsh
}
</script>
  <script lang="ts">
export default {
  name: 'user',
}
</script>
  <style >
.el-table .success-row {
  --el-table-tr-bg-color: rgba(220, 125, 177, 0.5);
}

.form {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
</style>
  